package lbframework.bean.fileChooser;

import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.HashSet;
import javax.swing.JFileChooser;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;
import lbframework.classe.Util;
import lbframework.bean.panel.LBPanel;

public class LBFileChooser extends LBPanel {

    private boolean obrigatorio = false;
    public final static String OPEN_DIALOG = "Open";
    public final static String SAVE_DIALOG = "Save";
    public final static String FILES_ONLY = "Files";
    public final static String DIRECTORIES_ONLY = "Directories";
    public final static int FILTER_TXT = 0;
    public final static int FILTER_XML = 1;
    private String dialogType = "";
    private String fileSelectionMode = "";
    private FileFilter fileFilter = null;
    private boolean teclaEnter = false;
    private String directory = "";

    public LBFileChooser() {
        initComponents();

        setDialogType(OPEN_DIALOG);
        setFileSelectionMode(FILES_ONLY);

        traduzir();

        setTeclaEnter(true);
    }

    public void abrir() throws Exception {
        txtArquivo.setText("");

        JFileChooser fileChooser = new JFileChooser();

        if (!directory.isEmpty()) {
            fileChooser.setCurrentDirectory(new File(directory));
        }

        if (fileSelectionMode.equals(FILES_ONLY)) {
            if (fileFilter != null) {
                fileChooser.addChoosableFileFilter(fileFilter);
            }

            fileChooser.setFileSelectionMode(javax.swing.JFileChooser.FILES_ONLY);

        } else if (fileSelectionMode.equals(DIRECTORIES_ONLY)) {
            fileChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
        }

        int retorno = 0;

        if (dialogType.equals(OPEN_DIALOG)) {
            fileChooser.setDialogType(javax.swing.JFileChooser.OPEN_DIALOG);
            fileChooser.setDialogTitle("Abrir");

            fileChooser.setCurrentDirectory(new File(directory));
            retorno = fileChooser.showOpenDialog(this);

        } else if (dialogType.equals(SAVE_DIALOG)) {
            fileChooser.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
            fileChooser.setDialogTitle("Salvar");

            retorno = fileChooser.showSaveDialog(this);
        }

        if (retorno == JFileChooser.APPROVE_OPTION) {
            setArquivo(fileChooser.getSelectedFile().getPath());
        }

    }

    public void setFileFilter(int fileFilter) throws Exception {
        if (fileFilter == FILTER_TXT) {
            this.fileFilter = new TxtFileFilter();

        } else if (fileFilter == FILTER_XML) {
            this.fileFilter = new XmlFileFilter();
        }
    }

    public String getArquivo() {
        return txtArquivo.getText();
    }

    public void setArquivo(String i_arquivo) {
        txtArquivo.setText(i_arquivo);
    }

    @Override
    public void setEnabled(boolean enabled) {
        txtArquivo.setEnabled(enabled);
        btnAbrir.setEnabled(enabled);

        setObrigatorio(obrigatorio);
    }

    public void setDirectory(String i_directory) {
        directory = i_directory.replace("\\", "\\\\");
    }

    private void traduzir() {
        UIManager.put("FileChooser.lookInLabelMnemonic", "E");
        UIManager.put("FileChooser.lookInLabelText", "Examinar em");
        UIManager.put("FileChooser.saveInLabelMnemonic", "S");
        UIManager.put("FileChooser.saveInLabelText", "Salvar em");
        UIManager.put("FileChooser.upFolderToolTipText", "Um nível acima");
        UIManager.put("FileChooser.upFolderAccessibleName", "Um nível acima");
        UIManager.put("FileChooser.homeFolderToolTipText", "Desktop");
        UIManager.put("FileChooser.homeFolderAccessibleName", "Desktop");
        UIManager.put("FileChooser.newFolderToolTipText", "Criar nova pasta");
        UIManager.put("FileChooser.newFolderAccessibleName", "Criar nova pasta");
        UIManager.put("FileChooser.listViewButtonToolTipText", "Lista");
        UIManager.put("FileChooser.listViewButtonAccessibleName", "Lista");
        UIManager.put("FileChooser.detailsViewButtonToolTipText", "Detalhes");
        UIManager.put("FileChooser.detailsViewButtonAccessibleName", "Detalhes");
        UIManager.put("FileChooser.fileNameLabelMnemonic", "N");
        UIManager.put("FileChooser.fileNameLabelText", "Nome do arquivo");
        UIManager.put("FileChooser.filesOfTypeLabelMnemonic", "A");
        UIManager.put("FileChooser.filesOfTypeLabelText", "Arquivos do tipo");
        UIManager.put("FileChooser.fileNameHeaderText", "Nome");
        UIManager.put("FileChooser.fileSizeHeaderText", "Tamanho");
        UIManager.put("FileChooser.fileTypeHeaderText", "Tipo");
        UIManager.put("FileChooser.fileDateHeaderText", "Data");
        UIManager.put("FileChooser.fileAttrHeaderText", "Atributos");
        UIManager.put("FileChooser.cancelButtonText", "Cancelar");
        UIManager.put("FileChooser.cancelButtonMnemonic", "C");
        UIManager.put("FileChooser.cancelButtonToolTipText", "Cancelar");
        UIManager.put("FileChooser.openButtonText", "Abrir");
        UIManager.put("FileChooser.openButtonEnable", "false");
        UIManager.put("FileChooser.openButtonMnemonic", "A");
        UIManager.put("FileChooser.openButtonToolTipText", "Abrir");
        UIManager.put("FileChooser.saveButtonText", "Salvar");
        UIManager.put("FileChooser.saveButtonToolTipText", "S");
        UIManager.put("FileChooser.saveButtonToolTipText", "Salvar");
        UIManager.put("FileChooser.updateButtonText", "Alterar");
        UIManager.put("FileChooser.updateButtonToolTipText", "A");
        UIManager.put("FileChooser.updateButtonToolTipText", "Alterar");
        UIManager.put("FileChooser.helpButtonText", "Ajuda");
        UIManager.put("FileChooser.helpButtonToolTipText", "A");
        UIManager.put("FileChooser.helpButtonToolTipText", "Ajuda");
        UIManager.put("FileChooser.acceptAllFileFilterText", "Todos os arquivos");
    }

    @Override
    public void requestFocus() {
        txtArquivo.requestFocus();
    }

    public boolean isTeclaEnter() {
        return teclaEnter;
    }

    public void setTeclaEnter(boolean teclaEnter) {
        this.teclaEnter = teclaEnter;

        HashSet kTab = new HashSet(1);
        kTab.add(KeyStroke.getKeyStroke("TAB"));

        if (teclaEnter) {
            kTab.add(KeyStroke.getKeyStroke("ENTER"));
        }

        txtArquivo.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, kTab);
    }

    public boolean isObrigatorio() {
        return obrigatorio;
    }

    public void setObrigatorio(boolean obrigatorio) {
        this.obrigatorio = obrigatorio;

        if (txtArquivo.isEnabled()) {
            if (obrigatorio) {
                txtArquivo.setBackground(Util.COR_OBRIGATORIO);
            } else {
                txtArquivo.setBackground(UIManager.getColor("TextField.background"));
            }
        } else {
            txtArquivo.setBackground(UIManager.getColor("TextField.disabledBackground"));
        }
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnAbrir = new lbframework.bean.button.LBButton();
        txtArquivo = new javax.swing.JTextField();

        setBorder(null);
        setPreferredSize(new java.awt.Dimension(285, 21));

        btnAbrir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lbframework/bean/fileChooser/abrir.png"))); // NOI18N
        btnAbrir.setToolTipText("Abrir (F9)");
        btnAbrir.setFocusable(false);
        btnAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAbrirActionPerformed(evt);
            }
        });

        txtArquivo.setPreferredSize(new java.awt.Dimension(331, 20));
        txtArquivo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtArquivoFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtArquivoFocusLost(evt);
            }
        });
        txtArquivo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtArquivoKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtArquivoKeyTyped(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(txtArquivo, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(btnAbrir, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(btnAbrir, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .add(txtArquivo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAbrirActionPerformed
        try {
            abrir();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, "Atenção");
        }
    }//GEN-LAST:event_btnAbrirActionPerformed

    private void txtArquivoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtArquivoKeyPressed
        try {
            if (evt.getKeyCode() == KeyEvent.VK_F9) {
                abrir();
            }

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, "Atenção");
        }
}//GEN-LAST:event_txtArquivoKeyPressed

    private void txtArquivoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtArquivoFocusGained
        if (txtArquivo.isEditable()) {
            Runnable doSelect = new Runnable() {

                public void run() {
                    txtArquivo.selectAll();
                }
            };

            SwingUtilities.invokeLater(doSelect);
        }
    }//GEN-LAST:event_txtArquivoFocusGained

    private void txtArquivoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtArquivoFocusLost
        try {
            if (!txtArquivo.getText().equals("")) {
                if (fileSelectionMode.equals(DIRECTORIES_ONLY)) {
                    String fileSeparator = System.getProperties().getProperty("file.separator");

                    if (!txtArquivo.getText().endsWith(fileSeparator)) {
                        txtArquivo.setText(txtArquivo.getText() + fileSeparator);
                    }
                }
            }

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, "Atenção");
        }
    }//GEN-LAST:event_txtArquivoFocusLost

    private void txtArquivoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtArquivoKeyTyped
    }//GEN-LAST:event_txtArquivoKeyTyped
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private lbframework.bean.button.LBButton btnAbrir;
    private javax.swing.JTextField txtArquivo;
    // End of variables declaration//GEN-END:variables

    public void setDialogType(String dialogType) {
        this.dialogType = dialogType;
    }

    public String getDialogType() {
        return this.dialogType;
    }

    public String getFileSelectionMode() {
        return this.fileSelectionMode;
    }

    public void setFileSelectionMode(String fileSelectionMode) {
        this.fileSelectionMode = fileSelectionMode;
    }

    private class TxtFileFilter extends FileFilter {

        public static final String FILE_EXTENSION = ".txt";

        public boolean accept(File f) {
            return f.getName().toLowerCase().endsWith(FILE_EXTENSION) || f.isDirectory();
        }

        public String getDescription() {
            return "Documentos de texto (*" + FILE_EXTENSION + ")";
        }
    }

    private class XmlFileFilter extends FileFilter {

        public static final String FILE_EXTENSION = ".xml";

        public boolean accept(File f) {
            return f.getName().toLowerCase().endsWith(FILE_EXTENSION) || f.isDirectory();
        }

        public String getDescription() {
            return "Extensible Markup Language (*" + FILE_EXTENSION + ")";
        }
    }
}
